﻿namespace Home.Services
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http.Filters;

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class OutputCacheAttribute : ActionFilterAttribute
    {
        public string MaxAge { get; set; }
        public bool MaxStale { get; set; }
        public string MaxStaleLimit { get; set; }
        public string MinFresh { get; set; }
        public bool MustRevalidate { get; set; }
        public bool NoCache { get; set; }
        public bool NoStore { get; set; }
        public bool NoTransform { get; set; }
        public bool OnlyIfCached { get; set; }
        public bool Private { get; set; }
        public bool ProxyRevalidate { get; set; }
        public bool Public { get; set; }
        public string SharedMaxAge { get; set; }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var header = new CacheControlHeaderValue()
            {
                MaxAge = this.MaxAge == null ? new TimeSpan?() : TimeSpan.Parse(this.MaxAge),
                MaxStale = this.MaxStale,
                MaxStaleLimit = this.MaxStaleLimit == null ? new TimeSpan?() : TimeSpan.Parse(this.MaxStaleLimit),
                MinFresh = this.MinFresh == null ? new TimeSpan?() : TimeSpan.Parse(this.MinFresh),
                MustRevalidate = this.MustRevalidate,
                NoCache = this.NoCache,
                NoStore = this.NoStore,
                NoTransform = this.NoTransform,
                OnlyIfCached = this.OnlyIfCached,
                Private = this.Private,
                ProxyRevalidate = this.ProxyRevalidate,
                Public = this.Public,
                SharedMaxAge = this.SharedMaxAge == null ? new TimeSpan?() : TimeSpan.Parse(this.SharedMaxAge),
            };

            if (actionExecutedContext != null && actionExecutedContext.Response != null && actionExecutedContext.Response.Headers != null)
            {
                actionExecutedContext.Response.Headers.CacheControl = header;
            }
        }
    }
}
